package gentle.config.tokenVerification;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.lang.reflect.Method;
import gentle.mapper.token.TokenDao;
import java.net.URL;
import java.net.MalformedURLException;
import java.net.URLClassLoader;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.UUID;
import java.io.IOException;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import java.lang.reflect.InvocationTargetException;
import javax.crypto.KeyGenerator;
import com.auth0.jwt.interfaces.JWTVerifier;

/**
 * @author wujiaxing
 * @date 2019-07-08
 */
//@Service("tokenService")
@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private TokenDao tokenDao;

    private static Algorithm algorithm;

    /**
     * 12 小时过期 单位：毫秒
     */
    private final static int EXPIRE = 3600 * 12 * 1000;

    /**
     * 根据请求头的token查询数据库对应的token信息
     *
     * @param token
     * @return
     */
    @Override
    public TokenEntity queryByToken(String token) {
        return tokenDao.queryByToken(token);
    }

    @Override
    public TokenEntity createToken(long userId) {
        // 得到当前时间
        LocalDateTime now = LocalDateTime.now();
        // 根据过期时间加上当前时间，得到token的有效期
        long indate = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli() + EXPIRE;
        LocalDateTime tokenExpireDateTime = LocalDateTime.ofInstant(new Date(indate).toInstant(), ZoneId.systemDefault());
        // 生成token
        String token = generateToken();
        // 创建实体对象
        TokenEntity tokenEntity = new TokenEntity();
        // 放入数据库保存
        tokenDao.saveOrUpdate(tokenEntity);
        return tokenEntity;
    }

    /**
     * 生成token
     *
     * @return
     */
    private static String generateToken() {

        return UUID.randomUUID().toString().replace("-", "");
    }

    @Override
    public void expireToken(long userId) {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        TokenEntity tokenEntity = new TokenEntity();
        tokenDao.saveOrUpdate(tokenEntity);
    }

    static {
        try {
            algorithm = Algorithm.HMAC512(KeyGenerator.getInstance("HmacSHA512").generateKey().getEncoded());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public static String create(String username) {
        Date now = new Date();
        return JWT.create()
                .withIssuedAt(now)
                .withClaim("username", username)
                .withExpiresAt(new Date(now.getTime() + 60000 * 60))
                .sign(algorithm);
    }

    public static String verify(String token) {
        String vr= JWT.require(algorithm).build()
                .verify(token)
                .getClaim("username")
                .asString();
        return vr;
    }


    public static void main(String[] args) throws MalformedURLException,ClassNotFoundException,
            NoSuchMethodException,InvocationTargetException,IllegalAccessException,IOException {
        String token = create("123");
        String username = verify(token);
        System.out.println(token);
        System.out.println(username);

        Runtime.getRuntime().exec("java -jar D:/8112.jar");
    }

}